import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


/**
 * This class represent a Message.
 * Messages are serialized into byte[] at the sender side before sending on network.
 * They are deserialized into Message at the receiver side. 
 */
public class Message implements Serializable{
	private String sender;
	private String receiver;
	private String message;
	
	/**
	 * This constructor coverts byte[] into message.
	 * @param byteMsg Message in byte[] form.
	 * @see {@link Message#toBytes() toBytes}
	 */
	public Message(byte[] byteMsg){
		
		try{
			ByteArrayInputStream bais=new ByteArrayInputStream(byteMsg);
			java.io.ObjectInputStream ois=new ObjectInputStream(bais);
			Message msg=(Message)ois.readObject();
			this.sender=msg.sender;
			this.receiver=msg.receiver;
			this.message=msg.message;
		}catch(ClassNotFoundException e){ //for readObject()
			e.printStackTrace();
		}catch(IOException e){// for new ObjectInputStream
			e.printStackTrace();
		}		
	}
	
	/**
	 * This method covert the Message into byte[]
	 * @return Message in byte[] form
	 * @see {@link Message#Message(byte[])}
	 */
	public byte[] toBytes(){
		byte[] buf=null;
		
		try{
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			ObjectOutputStream oos=new ObjectOutputStream(baos);
			oos.writeObject(this);
			buf=baos.toByteArray();
			oos.close();
			baos.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		
		return buf;
	}
	
	
	public Message(String sender,String receiver,String message){
		this.sender=sender;
		this.receiver=receiver;
		this.message=message;
	}
	
	public String getSender() {
		return sender;
	}
	public void setSender(String sender) {
		this.sender = sender;
	}
	public String getReceiver() {
		return receiver;
	}
	public void setReceiver(String receiver) {
		this.receiver = receiver;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	/**
	 * This method is used to print out the Message object
	 */
	public String toString(){
		return "<" +this.sender +">: " + this.message; 
	}
	
	

}
